import { Button, Form, Image } from "antd";
import React, { useMemo, useState } from "react";
import Upload from "../../Component/ResourceList/Upload";
import lodash from 'lodash';
import FileManage from "../../Component/FileManage";
import { UploadOutlined } from "@ant-design/icons";
import { Service } from "@/lib";
import styles from "./styles.module.scss";

interface ISourceEditProps {
    artType?: string;
    value?: any;
    onChange?: Function;
    sourceData?: any[]
}
const SourceEdit = (props: ISourceEditProps) => {
    const sourceData = props.sourceData || [];
    const [ showFileManage, setShowFileManage ] = useState(false);
    const [ defaultFiles ] = useState(() => {
        return typeof props.value === "string" ? JSON.parse(props.value) : [];
    })
    const [ selectedFiles, setSelectedFiles ] = useState<any[]>(defaultFiles);
    const serviceApi = Service.useService();
    const [ imgPref ] = useState(() => serviceApi.getUrl("resource.mediaUrl")); 
    const [ sourceList, setSourceList ] = useState<any[]>(props.sourceData || []);
    const filterType = useMemo(() => {
        const type = (props.artType as any) || "image";
        return type === "book" ? "pdf" : type;
    }, [props.artType]);
    
    return (
        <div>
            <Button style={{ display: "block", marginBottom: 5 }}
                onClick={() => setShowFileManage(true)}
                icon={<UploadOutlined />}
            >
                选择文件
            </Button>
            {
                props.artType === "image" && selectedFiles.map((item, index) => {
                    return <div key={index} className={styles.imageWrapper}><Image key={index} style={{maxWidth: 80, maxHeight: 80}} src={imgPref + "/" +item} alt={item.name} /></div>
                })
            }
            {
                props.artType !== "image" && sourceList.map((item) => {
                    return (
                        <Button type="link" key={item.id} style={{ display: "block", marginBottom: 2}}>{item.name}</Button>
                    );
                })
            }
            { showFileManage && <FileManage
                defaultSelected={selectedFiles}
                filterType={filterType}
                mulitpleSelected={["image","audio"].includes(props.artType || "")}
                onConfirm={(fileList, sourceList) => {
                    setSelectedFiles(fileList);
                    setSourceList(sourceList);
                    typeof props.onChange === "function" && props.onChange(JSON.stringify(fileList));
                    setShowFileManage(false);
                }}
                onCancel={() => {
                    setShowFileManage(false);
                }}
            /> }
            
        </div>
    );
};

export default SourceEdit;